package com.example.client_anna.module.branch_home;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.example.client_anna.R;
import com.example.client_anna.base.ActivityCollector;
import com.example.client_anna.base.BaseActivity;
import com.example.client_anna.module.ui.ViewCarrier;
import com.example.client_anna.network.okhttp3.HttpUtilImpl;
import com.example.client_anna.network.okhttp3.RequestUrl;
import com.example.client_anna.network.room.dao.GoodsDao;
import com.example.client_anna.network.room.database.ClientDataBase;
import com.example.client_anna.network.room.entity.Goods;
import com.example.client_anna.util.adapter.HomeShopOrderAdapter;
import com.example.client_anna.util.entity.Explore_data;
import com.example.client_anna.util.entity.HomeShopGroupItem;
import com.example.client_anna.util.entity.UserAddress;
import com.example.client_anna.util.tool.LocalThreadPools;
import com.example.client_anna.util.tool.PayResult;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.internal.FlowLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Formatter;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author cy
 * @email 272884043@qq.com
 * @date 2021/10/19
 */
public class HomeOrderActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "HomeOrderActivity";

    //服务器请求的加签订单信息
    private static final int INFO_PAY_SUCCESS = 200;
    //获取服务器加签订单信息失败
    private static final int INFO_PAY_FAIL = 500;
    //支付宝支付结果回调通知
    private static final int SDK_PAY_FLAG = 201;

    //用户配送地址信息
    private static final int USER_ADDRESS = 2;
    //用户还没有配送地址
    private static final int USER_ADDRESS_INIT = 3;

    //用户更改支付方式
    private static final int USER_PAY_CHANGE = 4;
    //用户更改配送时间
    private static final int USER_TIME_CHANGE = 5;

    //商家查询用户实际支付情况为成功支付，进行页面跳转
    private static final int SHOP_ORDER_SUCCESS = 6;

    private static String orderResult_id = "";

    //商家id,店铺名,所需的配送费
    private static String bid;
    private static String b_name;
    private static String b_distribution;//配送费
    private static String b_full;//满减

    //登录的用户信息
    private static String user_id;

    //用户配送地址信息
    private static String user_address_id;
    private static TextView user_name;
    private static TextView user_phone;
    private static TextView user_school;//学校地址
    private static TextView user_floor;//xx楼
    private static TextView user_dorm;//具体宿舍号

    //用户选择的支付方式，默认支付宝
    private static int user_choose_pay = 1;
    //用户选择的配送时间，默认对应上午或者下午的下课时间：11.40,6.00
    private static int user_choose_time = 1;

    //线程池
    private static ExecutorService executorService = LocalThreadPools.getExecutorService();
    private static GoodsDao dao;

    private RecyclerView order_recyclerview;
    //用户购买的订单信息
    private List<Goods> order_goods = new ArrayList<>();

    //选择时间和支付方式
    private BottomSheetDialog bottomSheetDialog_time;
    private BottomSheetDialog bottomSheetDialog_pay;

    //支付单选按钮
    private RadioGroup radioGroup;
    private RadioButton radio_alipay;
    private RadioButton radio_anna;

    //用户还没有选择自定义时间
    private static boolean custom_bool = false;

    private TextView ui_pay;
    private TextView ui_time;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_order);

        Toolbar toolbar = (Toolbar) findViewById(R.id.home_shop_order_toolbar);
        setSupportActionBar(toolbar);
        //系统自带导航栏
        ActionBar actionBar = getSupportActionBar();
        if(actionBar!=null){
            //系统自带的返回按钮
            actionBar.setDisplayHomeAsUpEnabled(true);
            //按钮图片
            actionBar.setHomeAsUpIndicator(R.drawable.details_back);
        }

        //点击事件的注册
        initClick();
        //获取并显示界面所需信息
        getOrderUiInfo();
        //获取用户购买的商品信息，并显示
        initData();
    }

    //点击事件的注册
    private void initClick() {
        //订单提交按钮的点击事件注册
        FrameLayout sub_order = (FrameLayout)findViewById(R.id.home_shop_order_submit);
        sub_order.setOnClickListener(this);

        //用户点击选择地址或添加新地址的点击事件注册
        LinearLayout add_address = (LinearLayout)findViewById(R.id.home_shop_order_add_address);
        add_address.setOnClickListener(this);

        //选择送餐时间的点击事件注册
        RelativeLayout choose_time = (RelativeLayout)findViewById(R.id.home_shop_order_choose_time);
        choose_time.setOnClickListener(this);

        //选择支付方式的点击事件注册
        RelativeLayout choose_pay= (RelativeLayout)findViewById(R.id.home_shop_order_choose_pay);
        choose_pay.setOnClickListener(this);
    }

    //界面所需信息，商家，用户
    private void getOrderUiInfo() {
        Intent intent = getIntent();
        bid = intent.getStringExtra("bid");
        b_name = intent.getStringExtra("b_name");
        b_distribution = intent.getStringExtra("b_distribution");//配送费
        b_full =intent.getStringExtra("b_full");//满减

        //获取登录用户的信息
        //访问存储在本地的文件，通过键值对的方式读取想要的信息出来
        SharedPreferences preferences =getSharedPreferences("UserInfo", Context.MODE_PRIVATE);
        user_id = preferences.getString("user_id","");

        //支付方式
        ui_pay = (TextView)findViewById(R.id.home_shop_order_choose_pay_text);
        //配送时间
        ui_time = (TextView)findViewById(R.id.home_shop_order_choose_time_text);

        //商户信息
        TextView shop_name = (TextView) findViewById(R.id.home_shop_order_name);
        shop_name.setText(b_name);//商家名
        TextView shop_dis = (TextView) findViewById(R.id.home_shop_order_dis);
        Float dis = Float.valueOf(b_distribution);//配送费
        //判断是否为0
        if(Math.abs(dis)<0.001){
            shop_dis.setText("0");
        }else {
            //不为0，如果小数点后为0，则取整
            if(dis.intValue()-dis==0.0){
                shop_dis.setText(String.valueOf(dis.intValue()));
            }else {
                shop_dis.setText(dis.toString());
            }
        }

        TextView shop_full = (TextView)findViewById(R.id.home_shop_order_full);
        shop_full.setText(b_full);
        shop_full.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//添加下划线

        //获取用户的默认地址
        Home_address_Okhttp3();
    }

    //获取用户购买的商品信息，并显示
    private void initData() {
        Log.d(TAG,"order "+"business bid "+bid+" "+b_name+" "+b_distribution);
        Log.d(TAG,"order "+"user_id "+user_id);

        dao = ClientDataBase.getDataBase(this).getGoodsDao();
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                order_goods = dao.queryGoodsByBid(bid);
                for (Goods i:order_goods){
                    Log.d(TAG,"order "+i.food_id);
                }
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        });

    }

    /*-------------------------------------获取用户配送地址------------------------------------------*/
    //用户的配送地址
    private void Home_address_Okhttp3() {
        //具体请求对象
        String info = "user_address";
        //链接的地址
        String address = RequestUrl.getUrl()+"user"+"?"+"request="+info;
        //创建RequestBody请求体,用于数据的提交
        RequestBody requestBody = new FormBody.Builder()
                .add("user_id",user_id)
                .build();
        HttpUtilImpl.sendOKHttpRequest(address, requestBody, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //onFailure方法用于网络请求失败后执行的语句
                //取消请求的判断，true用户主动关闭活动页面，false超时或者网络出错
                if(e.toString().contains("closed")){
                    //用户直接关闭页面后取消请求
                    call.cancel();
                }else{
                    //网络不稳定，或者无网络
                    Message message = new Message();
                    message.what = 400;
                    handler.sendMessage(message);
                    //取消请求
                    call.cancel();
                }
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //onResponse方法用于接收访成功后回调后的操作
                //得到response对象的具体内容
                String orderInfo=response.body().string();
                Log.d(TAG,"orderInfo "+orderInfo);
                //数据处理
                ParesJsonWithGSON_address(orderInfo);
            }
        });

    }
    private void ParesJsonWithGSON_address(String jsonData){
        if(!(jsonData.isEmpty())){
            Gson gson = new Gson();
            Boolean msg = false;
            JSONObject jsonObject = new JSONObject();
            jsonObject = JSON.parseObject(jsonData);

            if("200".equals(jsonObject.getString("status"))){
                String address = jsonObject.getString("data");
                Message message = new Message();
                message.what = USER_ADDRESS;
                message.obj = address;
                handler.sendMessage(message);
            }else {
                //用户还没有设置配送地址
                Message message = new Message();
                message.what = USER_ADDRESS_INIT;
                handler.sendMessage(message);
            }

        }

    }

    /*------------------获取用户加签订单信息，支付宝支付：拉起支付，餐到付款：直接跳转订单页面-----------------*/
    //加签订单信息请求，与订单信息提交
    //订单的信息：商家id 用户id 用户选择的配送地址id 支付方式 配送时间 购买的商品详细信息
    private void Home_Order_Okhttp3(String user_order) {

        Log.d(TAG,"submit_bid "+bid);
        Log.d(TAG,"submit_user_id "+user_id);
        Log.d(TAG,"submit_user_address "+user_address_id);
        Log.d(TAG,"submit_user_order "+user_order);

        String pay = "支付宝";
        if(user_choose_pay==1){
            pay = "支付宝";
            Log.d(TAG,"submit_user_pay "+pay);
        }else {
            pay = "餐到付款";
            Log.d(TAG,"submit_user_pay "+pay);
        }

        String submit_time = ui_time.getText().toString();
        Log.d(TAG,"submit_user_time "+submit_time);

        //具体请求对象
        String info = "order_info";
        //链接的地址
        String address = RequestUrl.getUrl()+"home"+"?"+"request="+info;
        //创建RequestBody请求体,用于数据的提交
        RequestBody requestBody = new FormBody.Builder()
                .add("submit_bid",bid)
                .add("submit_user_id",user_id)
                .add("submit_user_address_id",user_address_id)
                .add("submit_user_order",user_order)
                .add("submit_user_pay",String.valueOf(user_choose_pay))
                .add("submit_user_time",submit_time)
                .build();
        HttpUtilImpl.sendOKHttpRequest(address, requestBody, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //onFailure方法用于网络请求失败后执行的语句
                //取消请求的判断，true用户主动关闭活动页面，false超时或者网络出错
                if(e.toString().contains("closed")){
                    //用户直接关闭页面后取消请求
                    call.cancel();
                }else{
                    //网络不稳定，或者无网络
                    Message message = new Message();
                    message.what = 400;
                    handler.sendMessage(message);
                    //取消请求
                    call.cancel();
                }
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //onResponse方法用于接收访成功后回调后的操作
                //得到response对象的具体内容
                String orderInfo=response.body().string();
                Log.d(TAG,"orderInfo "+orderInfo);
                //数据处理
                ParesJsonWithGSON(orderInfo);
            }
        });

    }
    //处理服务端返回的json数据
    private List<HomeShopGroupItem> items;
    private void ParesJsonWithGSON(String jsonData){
        if(!(jsonData.isEmpty())){
            Gson gson = new Gson();
            Boolean msg = false;
            JSONObject jsonObject = new JSONObject();
            jsonObject = JSON.parseObject(jsonData);

            if("success".equals(jsonObject.getString("status"))){

                if("2".equals(jsonObject.getString("user_pay"))) {
                    //选择餐到付款，清空用户在该商家购买的商品缓存信息
                    List<Goods> goods = dao.queryGoodsByBid(bid);

                    for (Goods i: goods){
                        dao.deleteGoods(i);
                    }

                    //餐到付费，直接跳转到订单模块
                    Message message = new Message();
                    message.what = SHOP_ORDER_SUCCESS;
                    handler.sendMessage(message);
                }else {
                    //支付宝支付
                    String orderInfo_gson = jsonObject.getString("order_Countersign");
                    Log.d(TAG, "orderInfo_gson " + orderInfo_gson);

                    orderResult_id = jsonObject.getString("order_id");

                    //传递加签的订单信息给Pay()方法拉起支付宝支付
                    Message message = new Message();
                    message.what = INFO_PAY_SUCCESS;
                    message.obj = orderInfo_gson;
                    handler.sendMessage(message);
                }
            }else {
                Message message = new Message();
                message.what = INFO_PAY_FAIL;
                handler.sendMessage(message);
            }

        }

    }

    /*----------------商家确认该订单支付状态，支付宝支付的成功与失败，餐到付款直接跳转订单页面-----------------*/
    private void Home_OrderSub_Okhttp3(String status,String result) {
        
        if(!"".equals(orderResult_id)) {
            //具体请求对象
            String info = "order_result";
            //链接的地址
            String address = RequestUrl.getUrl() + "home" + "?" + "request=" + info;
            //创建RequestBody请求体,用于数据的提交
            RequestBody requestBody = new FormBody.Builder()
                    .add("client_status",status)
                    .add("order_id",orderResult_id)
                    .add("result",result)
                    .build();
            HttpUtilImpl.sendOKHttpRequest(address, requestBody, new okhttp3.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //onFailure方法用于网络请求失败后执行的语句
                    //取消请求的判断，true用户主动关闭活动页面，false超时或者网络出错
                    if (e.toString().contains("closed")) {
                        //用户直接关闭页面后取消请求
                        call.cancel();
                    } else {
                        //网络不稳定，或者无网络
                        Message message = new Message();
                        message.what = 400;
                        handler.sendMessage(message);
                        //取消请求
                        call.cancel();
                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    //onResponse方法用于接收访成功后回调后的操作
                    //得到response对象的具体内容
                    String orderInfo = response.body().string();
                    //数据处理
                    ParesJsonWithGSON_orderSub(orderInfo);
                }
            });
        }
    }

    private void ParesJsonWithGSON_orderSub(String jsonData){
        if(!(jsonData.isEmpty())){
            JSONObject jsonObject = new JSONObject();
            jsonObject = JSON.parseObject(jsonData);
            if("success".equals(jsonObject.getString("status"))){
                //成功支付清空用户在该商家购买的商品缓存信息
                List<Goods> goods = dao.queryGoodsByBid(bid);

                for (Goods i: goods){
                    dao.deleteGoods(i);
                }
                //进行页面跳转
                Message message = new Message();
                message.what = SHOP_ORDER_SUCCESS;
                handler.sendMessage(message);
            }

        }

    }

    /*---------------------------获取到加签订单后，调用该方法拉起支付------------------------------------*/
    //拉起支付宝支付
    private void Pay(String orderInfo){
        
        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(HomeOrderActivity.this);
                Map<String,String> result = alipay.payV2(orderInfo,true);
                Log.i("msp", result.toString());

                //回调处理
                Message message = new Message();
                message.what = SDK_PAY_FLAG;
                message.obj = result;
                handler.sendMessage(message);
            }
        };

        //必须异步处理
        Thread payThread = new Thread(runnable);
        payThread.start();
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 1:
                    try {
                        order_recyclerview = (RecyclerView) findViewById(R.id.home_shop_order_recyclerview);
                        HomeShopOrderAdapter homeShopOrderAdapter = new HomeShopOrderAdapter(order_goods);
                        //GridLayoutManager布局方式，参数1:Context，参数2:列数
                        GridLayoutManager layoutManager = new GridLayoutManager(HomeOrderActivity.this, 1);
                        //加载布局方式
                        order_recyclerview.setLayoutManager(layoutManager);
                        order_recyclerview.setFocusable(true);
                        //加载闪烁问题：添加标记tag,tag标记着每一张请求url的图片，加载的时候防止重新加载
                        //需要重写adapter的getItemId方法
                        homeShopOrderAdapter.setHasStableIds(true);
                        //recyclerView布局加载适配器
                        order_recyclerview.setAdapter(homeShopOrderAdapter);
                    }catch (Exception e){
                        e.printStackTrace();
                    }finally {
                        Log.d(TAG,"order "+"rec");
                    }

                    TextView shop_sum = (TextView)findViewById(R.id.home_shop_order_sum);
                    Float sum = 0.0f;
                    for (Goods i:order_goods){
                        sum+=i.food_price*i.food_amount;
                    }
                    //小计
                    DecimalFormat decimalFormat = new DecimalFormat(".00");//保留俩位小数
                    shop_sum.setText(decimalFormat.format(sum));

                    TextView shop_sum_sub = (TextView)findViewById(R.id.home_shop_order_sum_sub);
                    Float sum_sub = sum+Float.valueOf(b_distribution);//加配送费

                    shop_sum_sub.setText(decimalFormat.format(sum_sub-Float.valueOf(b_full)));//满减，最后显示的价格，合计
                    break;
                case 400:
                    //请求服务器数据失败
                    Toast.makeText(HomeOrderActivity.this,"服务器异常，请等待！",Toast.LENGTH_SHORT).show();
                    break;
                case HomeOrderActivity.INFO_PAY_SUCCESS:
                    String orderInfo = msg.obj.toString();
                    //调用Pay()方法拉起支付宝支付
                    Pay(orderInfo);
                    break;
                case HomeOrderActivity.INFO_PAY_FAIL:
                    //请求服务器加签订单信息失败
                    Toast.makeText(HomeOrderActivity.this,"获取加签订单信息失败，请重新获取",Toast.LENGTH_SHORT).show();
                    break;
                case HomeOrderActivity.SDK_PAY_FLAG:
                    //支付宝支付结果通知
                    PayResult payResult = new PayResult((Map<String,String>) msg.obj);
                    String resultStatus = payResult.getResultStatus();
                    String result = payResult.getResult();
                    Log.d(TAG,"trade_no "+ result);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        //商家确认实际支付状态
                        Home_OrderSub_Okhttp3("success",result);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(HomeOrderActivity.this,"支付失败，请重新支付",Toast.LENGTH_SHORT).show();
                        Home_OrderSub_Okhttp3("fail",result);
                    }
                    break;
                case HomeOrderActivity.USER_ADDRESS:
                    List<UserAddress> list = new ArrayList<>();
                    Gson gson = new Gson();

                    //转换json数组，使用List<UserAddress>接收
                    //最新请求的数据
                    list = gson.fromJson(msg.obj.toString(), new TypeToken<List<UserAddress>>(){
                    }.getType());

                    //取出用户的默认地址
                    UserAddress userAddress = new UserAddress();
                    for (UserAddress i:list){
                        Log.i("user_address",i.getAid());
                        if("0".equals(i.getIs_default())) {
                            userAddress = i;
                            break;
                        }
                    }

                    //传递用户确认订单界面用户选择的配送地址id
                    user_address_id = userAddress.getAid();

                    user_name = (TextView)findViewById(R.id.home_shop_order_user_name);
                    user_phone = (TextView)findViewById(R.id.home_shop_order_user_phone);
                    user_school = (TextView)findViewById(R.id.home_shop_order_user_school);
                    user_floor = (TextView)findViewById(R.id.home_shop_order_user_floor);
                    user_dorm = (TextView)findViewById(R.id.home_shop_order_user_dorm);

                    user_name.setText(userAddress.getU_name());
                    user_phone.setText(userAddress.getPhone());
                    user_school.setText(userAddress.getSchool());
                    user_floor.setText(userAddress.getFloor());
                    user_dorm.setText(userAddress.getDorm());
                    break;
                case HomeOrderActivity.USER_ADDRESS_INIT:
                    user_name = (TextView)findViewById(R.id.home_shop_order_user_name);
                    user_phone = (TextView)findViewById(R.id.home_shop_order_user_phone);
                    user_school = (TextView)findViewById(R.id.home_shop_order_user_school);
                    user_floor = (TextView)findViewById(R.id.home_shop_order_user_floor);
                    user_dorm = (TextView)findViewById(R.id.home_shop_order_user_dorm);

                    user_name.setText("");
                    user_phone.setText("");
                    user_school.setText("请点击添加默认配送地址信息");
                    user_floor.setText("");
                    user_dorm.setText("");
                    break;
                case HomeOrderActivity.USER_PAY_CHANGE:
                    if(user_choose_pay==1){
                        ui_pay.setText("支付宝");
                    }else {
                        ui_pay.setText("餐到付款");
                    }
                    break;
                case HomeOrderActivity.USER_TIME_CHANGE:
                    switch (user_choose_time){
                        case 1:
                            ui_time.setText("立即送达");
                            custom_bool = false;
                            break;
                        case 2:
                            ui_time.setText("下课时间");
                            custom_bool = false;
                            break;
                        case 3:
                            if(custom_bool==false) {
                                ui_time.setText(msg.obj.toString());
                                custom_bool = true;
                            }
                            break;
                    }
                    break;
                case HomeOrderActivity.SHOP_ORDER_SUCCESS:
                    Toast.makeText(HomeOrderActivity.this,"开始进行页面跳转",Toast.LENGTH_SHORT).show();
                    ActivityCollector.finishAll();//移除所有活动
                    Intent intent = new Intent(HomeOrderActivity.this, ViewCarrier.class);//跳转到主界面

                    Bundle bundle = new Bundle();
                    bundle.putInt("module_status",2);

                    intent.putExtras(bundle);

                    startActivity(intent);
                    break;
            }
        }
    };

    //返回按钮点击事件，返回上一个活动
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //该活动关闭，关闭线程池
        LocalThreadPools.ShutdownLocalThreadPools();
    }

    //从被覆盖的状态重新回到栈顶，被显示在用户面前执行该方法
    @Override
    protected void onResume() {
        super.onResume();
        user_choose_pay = 1;
        user_choose_time = 1;
    }


    /*----------------------------------------页面点击事件------------------------------------------*/
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.home_shop_order_submit:
                Toast.makeText(HomeOrderActivity.this,"获取加签订单信息",Toast.LENGTH_SHORT).show();
                if(user_choose_pay==1){
                    //支付宝支付
                    //生成用户购买的商品订单信息，转换成json进行传输
                    Gson gson = new Gson();
                    if(order_goods!=null&&!order_goods.isEmpty()) {
                        String json = gson.toJson(order_goods);
                        //向服务端提交订单信息，并生成加签的订单信息，拉起支付宝支付
                        Log.i("user_order ", json);
                        Home_Order_Okhttp3(json);
                    }else {
                        Toast.makeText(HomeOrderActivity.this,"请至少购买一件商品",Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Gson gson = new Gson();
                    if(order_goods!=null&&!order_goods.isEmpty()) {
                        //餐到付费
                        String json = gson.toJson(order_goods);
                        Home_Order_Okhttp3(json);
                    }else {
                        Toast.makeText(HomeOrderActivity.this,"请至少购买一件商品",Toast.LENGTH_SHORT).show();
                    }
                }

                break;
            case R.id.home_shop_order_add_address:
                Toast.makeText(HomeOrderActivity.this,"选择或添加新地址",Toast.LENGTH_SHORT).show();
                break;
            case R.id.home_shop_order_choose_time:
                Toast.makeText(HomeOrderActivity.this,"选择送餐时间",Toast.LENGTH_SHORT).show();
                chooseTimeBottom();
                break;
            case R.id.home_shop_order_choose_pay:
                //选择支付方式
                choosePayBottom();
                break;
        }
    }

    /*-------------------------------------底部弹窗选择支付方式---------------------------------------*/
    //选择支付方式
    private void choosePayBottom() {
        //实例化BottomSheetDialog
        //参数1：当前context 参数2：背景透明化
        bottomSheetDialog_pay = new BottomSheetDialog(this,R.style.BottomSheetDialog);
        View view = getLayoutInflater().inflate(R.layout.dialog_home_shop_order_pay,null);
        bottomSheetDialog_pay.setContentView(view);

        //监听用户选择的支付方式
        radioGroup = (RadioGroup)view.findViewById(R.id.dialog_pay_rad0);
        radioGroup.setOnCheckedChangeListener(new RadioButtonListener());

        radio_alipay = (RadioButton)view.findViewById(R.id.dialog_pay_rad1);
        radio_anna = (RadioButton)view.findViewById(R.id.dialog_pay_rad2);

        if(user_choose_pay==1){
            radio_alipay.setChecked(true);
            radio_anna.setChecked(false);
        }else {
            radio_alipay.setChecked(false);
            radio_anna.setChecked(true);
        }

        bottomSheetDialog_pay.show();

        //点击关闭支付方式的选择
        ImageView dialog_pay_exit = (ImageView)view.findViewById(R.id.dialog_pay_exit);
        dialog_pay_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog_pay.dismiss();
            }
        });

    }
    class RadioButtonListener implements RadioGroup.OnCheckedChangeListener{
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId){
                case R.id.dialog_pay_rad1:
                    //支付宝支付
                    Log.d("type","支付宝支付");
                    user_choose_pay = 1;
                    bottomSheetDialog_pay.dismiss();
                    break;
                case R.id.dialog_pay_rad2:
                    //餐到付费
                    Log.d("type","餐到付费");
                    user_choose_pay = 2;
                    bottomSheetDialog_pay.dismiss();
                    break;
            }
            //更新ui界面
            Message message = new Message();
            message.what = USER_PAY_CHANGE;
            handler.sendMessage(message);
        }
    }

    /*-------------------------------------底部弹窗选择配送时间---------------------------------------*/
    //选择配送时间
    private void chooseTimeBottom() {
        //实例化BottomSheetDialog
        //参数1：当前context 参数2：背景透明化
        bottomSheetDialog_time = new BottomSheetDialog(this,R.style.BottomSheetDialog);
        View view = getLayoutInflater().inflate(R.layout.dialog_home_shop_order_time,null);
        bottomSheetDialog_time.setContentView(view);

        //选择时间单选按钮
        RadioGroup radioGroup_time;
        RadioButton radio_immediately;//立即送到
        RadioButton radio_over;//下课时间
        RadioButton radio_custom;//自定义时间

        //监听用户选择的配送时间
        radioGroup_time = (RadioGroup)view.findViewById(R.id.home_dialog_time_rad0);
        radioGroup_time.setOnCheckedChangeListener(new RadioButtonListener_time());

        radio_immediately = (RadioButton)view.findViewById(R.id.home_dialog_time_rad1);
        radio_over = (RadioButton)view.findViewById(R.id.home_dialog_time_rad2);
        radio_custom = (RadioButton)view.findViewById(R.id.home_dialog_time_rad3);

        custom_bool = false;
        switch (user_choose_time){
            case 1:
                radio_immediately.setChecked(true);
                radio_over.setChecked(false);
                radio_custom.setChecked(false);
                break;
            case 2:
                radio_immediately.setChecked(false);
                radio_over.setChecked(true);
                radio_custom.setChecked(false);
                break;
            case 3:
                radio_immediately.setChecked(false);
                radio_over.setChecked(false);
                radio_custom.setChecked(false);
                break;
        }

        bottomSheetDialog_time.show();
        //点击关闭支付方式的选择
        ImageView dialog_time_exit = (ImageView)view.findViewById(R.id.home_dialog_time_exit);
        dialog_time_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog_time.dismiss();
            }
        });

    }
    class RadioButtonListener_time implements RadioGroup.OnCheckedChangeListener{
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId){
                case R.id.home_dialog_time_rad1:
                    user_choose_time = 1;
                    bottomSheetDialog_time.dismiss();
                    break;
                case R.id.home_dialog_time_rad2:
                    user_choose_time = 2;
                    bottomSheetDialog_time.dismiss();
                    break;
                case R.id.home_dialog_time_rad3:
                    //选择自定义时间显示输入框供用户进行选择
                    user_choose_time = 3;
                    bottomSheetDialog_time.dismiss();
                    if(custom_bool==false) {
                        //用户选择其他时间
                        userChooseTime();
                        return;
                    }
                    break;
            }
            //更新ui界面
            Message message = new Message();
            message.what = USER_TIME_CHANGE;
            handler.sendMessage(message);
        }
    }
    //用户选择其他时间
    private void userChooseTime(){
        Calendar currentDate = Calendar.getInstance();//当前时间
        TimePickerView pickerView = new TimePickerBuilder(HomeOrderActivity.this
                , new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View view) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String custom_time = format.format(date);
                //更新ui界面
                Message message = new Message();
                message.what = USER_TIME_CHANGE;
                message.obj = custom_time;
                handler.sendMessage(message);
            }
        }).setType(new boolean[]{false,false,true,true,true,false})
                .setRangDate(currentDate,currentDate)
                .setSubmitColor(getResources().getColor(R.color.main_color_tone))
                .setCancelColor(getResources().getColor(R.color.main_color_tone))
                .build();
        pickerView.show();
    }

}